package org.cis.jproyinv.negocio;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.JOptionPane;

public class UseCaseController {

    public void respaldarBaseDeDatos() {
        try {
            SimpleDateFormat fecha = new SimpleDateFormat();
            Calendar tiempoActual = Calendar.getInstance();
            fecha = new SimpleDateFormat("dd,MM,yy,HH-mm-ss");
            String tiempo = fecha.format(tiempoActual.getTime());
            // Comando:
            String comando = "";
            comando = "C:/Program Files/PostgreSQL/8.4/bin/pg_dump";
            String archivo = "D:\\Respaldo DB\\" + " jproyinvDB " + " - " + tiempo + ".backup";
            File backupFile = new File("D:\\Respaldo DB\\" + " Operaciones " + " - " + tiempo + ".backup");
            FileWriter fw = new FileWriter(backupFile);

            Runtime r;

            //PostgreSQL variables
            String user = "postgres";
            String dbase = "jproyinvDB";
            String password = "unlmax90";


            Process p;
            ProcessBuilder pb;

            //Ejecucion del proceso de respaldo

            r = Runtime.getRuntime();
            pb = new ProcessBuilder(comando, "-h", "localhost", "-p", "5432", "-U", user, "-F", "c", "-b", "-v", "-f", archivo, dbase);
            pb.environment().put("PGPASSWORD", password);
            pb.redirectErrorStream(true);

            p = pb.start();
            InputStreamReader irs = new InputStreamReader(p.getInputStream());
            BufferedReader br = new BufferedReader(irs);

            String line;
            while ((line = br.readLine()) != null) {
                fw.write(line + "\n");
            }
            fw.close();
            irs.close();
            br.close();

            JOptionPane.showMessageDialog(null, "La base de datos se respaldo correctamente", "Excelente", JOptionPane.INFORMATION_MESSAGE);

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Error: \n" + e);
        }
    }
}
